package br.consultorio.digital.dao;

import java.util.ArrayList;

import android.app.Activity;
import br.consultorio.digital.modelo.entidade.Agenda;
import br.consultorio.digital.modelo.entidade.Medico;

public class DAOAgenda extends DAO {

	// private Activity activityAtividadeData;
	private static DAOAgenda instance;

	public static DAOAgenda getInstance(Activity context) {
		if (instance == null) {
			synchronized (DAOAgenda.class) {

				if (instance == null) {
					instance = new DAOAgenda();
					abrecriaBanco(context);
				}
			}
		}
		return instance;
	}

	public ArrayList<Object> consultarAgenda(String data, int medico) {
		setCursor(getDatabase()
				.query("tb_agenda as a, tb_medico as m",
						new String[] { "distinct a.ID_Agenda, a.DT_Agenda, a.ID_Medico, m.NM_Medico" },
						"a.id_medico = m.id_medico and a.dt_agenda like '"
								+ data + "' and a.id_medico = " + medico,
						null,
						null,
						null,
						"SUBSTR(a.dt_agenda, 7, 4), SUBSTR(a.dt_agenda, 4, 2), SUBSTR(a.dt_agenda, 1, 2)"));

		ArrayList<Object> ap = new ArrayList<Object>();

		while (getCursor().moveToNext()) {
			ap.add(getAgenda());
		}

		fechaBanco();
		return ap;
	}

	public ArrayList<Object> consultarTodos() {
		setCursor(getDatabase()
				.query("tb_agenda as a, tb_medico as m",
						new String[] { "distinct a.ID_Agenda, a.DT_Agenda, a.ID_Medico, m.NM_Medico" },
						null,
						null,
						null,
						null,
						"SUBSTR(a.dt_agenda, 7, 4), SUBSTR(a.dt_agenda, 4, 2), SUBSTR(a.dt_agenda, 1, 2)"));

		ArrayList<Object> ap = new ArrayList<Object>();

		while (getCursor().moveToNext()) {
			ap.add(getAgenda());
		}

		fechaBanco();
		return ap;
	}

	private Agenda getAgenda() {
		Agenda a = new Agenda();

		a.setId_agenda(getCursor().getInt(
				getCursor().getColumnIndexOrThrow("ID_Agenda")));

		Medico m = new Medico();

		m.setId_medico(getCursor().getInt(
				getCursor().getColumnIndexOrThrow("ID_Medico")));
		m.setNm_medico(getCursor().getString(
				getCursor().getColumnIndexOrThrow("NM_Medico")));

		a.setMedico(m);

		a.setDt_agenda(getCursor().getString(
				getCursor().getColumnIndexOrThrow("DT_Agenda")));

		return a;
	}
}
